#include <sstream>
#include "GameConfig.h"
//#include "GamePlayer.h" not needed as long as GrudgeEvaluator is a GamePlayer descendant
#include "GrudgeEvaluator.h"

GameMasterConfig*	GameMasterConfig::MASTER;
unsigned int		GameMasterConfig::nextPlayerID;
GamePlayerConfig*	GamePlayerConfig::PLAYER;
GamePlayer*			GamePlayerConfig::player;

void GameMasterConfig::loadDetails(text_iarchive& ar)
{
	ar & nextPlayerID;
} // end GameConfig method

unsigned int GameMasterConfig::obtainUniqueID()
{
	if (NULL == MASTER)
		new GameMasterConfig();

	unsigned int returnValue = nextPlayerID;
	++nextPlayerID;
	
	try
	{
		MASTER->save();
	} catch(...)
	{
	} // end try

	return returnValue;
} // end method

void GameMasterConfig::saveDetails(text_oarchive& ar)
{
	ar & nextPlayerID;
} // end GameConfig method

void GamePlayerConfig::buildAccountLocation(string& accountName)
{
	static string accountPath("./accounts/");
	boost::filesystem::path dir(accountPath);
	boost::filesystem::create_directory(dir);
	accountName = accountPath + accountName;
}

void GamePlayerConfig::loadDetails(text_iarchive& ar)
{
	ar & player->systemUniqueID;
} // end GameConfig method

GamePlayerConfig& GamePlayerConfig::of(GamePlayer* p)
{
	if (NULL == PLAYER)
		PLAYER = new GamePlayerConfig();

	player = p;
	buildAccountLocation(PLAYER->filePath = p->getAccountName());
	return *PLAYER;
} // end method

int GamePlayerConfig::rename(string& newName)	
{
	string newLocation(newName);
	buildAccountLocation(newLocation);
	return std::rename(filePath.c_str(), newLocation.c_str());
} // end method

void GamePlayerConfig::saveDetails(text_oarchive& ar)
{
	if (GamePlayer::IDENTITY_NOT_ESTABLISHED == player->systemUniqueID)
		player->systemUniqueID = GameMasterConfig::obtainUniqueID();

	ar & player->systemUniqueID;
} // end GameConfig method

GrudgeConfig* GrudgeConfig::forRecord(GamePlayer* p)
{
	std::ostringstream aiPath;
	aiPath << aiFolder << p->getSystemUniqueID();
	filePath = aiPath.str();

	return this;
} // end method

void GrudgeConfig::loadDetails(text_iarchive& ar)
{
	ar & ai->records[ai->recordCount].score;
} // end GameConfig method

GrudgeConfig* GrudgeConfig::of(GrudgeEvaluator* ai)
{
	GrudgeConfig* cfg = new GrudgeConfig();
	static string accountPath("./ai/");
	{
		boost::filesystem::path dir(accountPath);
		boost::filesystem::create_directory(dir);
	}

	std::ostringstream aiPath;
	aiPath << accountPath << ai->getSystemUniqueID() << "/";
	cfg->aiFolder = aiPath.str();
	{
		boost::filesystem::path dir(cfg->aiFolder);
		boost::filesystem::create_directory(dir);
	}

	cfg->ai = ai;
	return cfg;
} // end method

void GrudgeConfig::saveDetails(text_oarchive& ar)
{
	ar & ai->records[ai->recordCount].score;
} // end GameConfig method
